package com.guoyh.baseutils.utils

import android.animation.Animator
import android.view.View
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import com.guoyh.baseutils.ext.inVisible
import com.guoyh.baseutils.ext.visible

/**
 * @CreateDate: 7/27/21 1:48 PM
 * @Author: guoyh
 * @Description: java类作用描述
 */


fun View.animShake() {
    setYoYoAnim(Techniques.Shake)
}

fun View.animFadeInRight(animInit: (YoYo.AnimationComposer.() -> Unit)? = null): YoYo.YoYoString =
    setYoYoAnim(Techniques.FadeInRight, 500, animInit)


fun View.animFadeOutLeft(animInit: (YoYo.AnimationComposer.() -> Unit)? = null): YoYo.YoYoString =
    setYoYoAnim(Techniques.FadeOutLeft, 500, animInit)

fun View.animTada() {
    setYoYoAnim(Techniques.Tada)
}

fun View.animSwing() {
    setYoYoAnim(Techniques.Swing)
}

fun View.animRubberband() {
    setYoYoAnim(Techniques.RubberBand, 500)

}


/**
 * 左边出 右边进  动画 移动+渐隐
 */
fun animFadeLeftOutRightIn(inView: View, outView: View, duration: Long) {
    outView.animFadeOutLeft {
        withListener(WithAnimCallBack {
            outView.inVisible()
        })

    }
    inView.postDelayed({
        inView.animFadeInRight {
            withListener(WithAnimCallBack({
                inView.alpha = 0f
                inView.visible()
            }))
        }

    }, duration)
}


private fun View.setYoYoAnim(
    techniques: Techniques,
    duration: Long = 1000,
    animInit: (YoYo.AnimationComposer.() -> Unit)? = null
) =
    YoYo.with(techniques).let {
        it.duration(duration)
//                                .repeat(YoYo.INFINITE)
//        pivot(0.5F, 0.5F)
//        interpolate(AccelerateDecelerateInterpolator())

        animInit?.invoke(it)
        it.playOn(this@setYoYoAnim)
    }

class WithAnimCallBack(val start: (() -> Unit)? = null, val end: (() -> Unit)? = null) :
    Animator.AnimatorListener {
    override fun onAnimationStart(animation: Animator?) {
        start?.invoke()
    }

    override fun onAnimationEnd(animation: Animator?) {
        end?.invoke()
    }

    override fun onAnimationCancel(animation: Animator?) {
    }

    override fun onAnimationRepeat(animation: Animator?) {
    }

}
